package com.sparrow.common.hotswap2;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class HotSwapClassLoader extends ClassLoader {
    private final String moduleName;
    private final File classPath;
    private final int version;

    public HotSwapClassLoader(String moduleName, File classPath, int version,
                              ClassLoader parent) {
        super(parent);
        this.moduleName = moduleName;
        this.classPath = classPath;
        this.version = version;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String fileName = name.replace('.', '/') + ".class";
        File classFile = new File(classPath, fileName);

        if (classFile.exists()) {
            try {
                byte[] classBytes = Files.readAllBytes(classFile.toPath());
                Class<?> clazz = defineClass(name, classBytes, 0, classBytes.length);
                return clazz;
            } catch (IOException e) {
                throw new ClassNotFoundException("Failed to load class: " + name, e);
            }
        }

        throw new ClassNotFoundException("Class not found: " + name);
    }

    @Override
    public String toString() {
        return "HotSwapClassLoader{" +
                "moduleName='" + moduleName + '\'' +
                ", version=" + version +
                '}';
    }

    public void clearCache() {

    }
}
